#include "Queue.h"
#include <stdlib.h>
#include <stdio.h>

int verificationQueue(Queue *queue) {
    return queue != NULL && queue->data != NULL;
}

// 初始化队列
Queue *initQueue(int size) {
    Queue *queue = malloc(sizeof *queue);
    if (size <= 0) {
        size = QueueMaxSize;
    }
    queue->size = size;
    queue->data = malloc(size * sizeof(ElemType));
    queue->front = queue->rear = 0;

    return queue;
}

// 入队列
int enQueue(Queue *queue, ElemType e) {
    // 判断队列满
    if (!verificationQueue(queue) || (queue->rear + 1) % queue->size == queue->front) {
        return 0;
    }
    queue->rear = ++queue->rear % queue->size;
    queue->data[queue->rear] = e;
    return 1;
}

// 出队列
ElemType deQueue(Queue *queue) {
    // 判断队列是否为空
    if (!verificationQueue(queue) || queue->rear == queue->front) {
        return 0;
    }
    queue->front = ++queue->front % queue->size;
    ElemType temp = queue->data[queue->front];
    // 注意：出队列需要置为空
    queue->data[queue->front] = ' ';
    return temp;
}

// 输出队列
void showQueue(Queue *queue) {
    // 判断队列是否为空
    if (!verificationQueue(queue) || queue->rear == queue->front) {
        return;
    }
    printf("长度：%d ==> [", queue->rear - queue->front);
    for (int i = queue->front + 1; i <= queue->rear; ++i) {
        printf("'%c'", queue->data[i]);
        if (i == queue->rear) {
            printf("]\n");
        } else {
            printf(",");
        }
    }
}

// 队列长度
int queueLength(Queue *queue) {
    if (!verificationQueue(queue)) {
        return 0;
    }
    return queue->rear - queue->front;
}

// 判断队列是否为空
int isEmptyQueue(Queue *queue) {
    return !verificationQueue(queue) || queue->rear == queue->front;
}

// 释放内存
void deleteQueue(Queue *queue) {
    if (queue == NULL) {
        return;
    }
    if (queue->data != NULL) {
        free(queue->data);
        queue->data = NULL;
    }
    free(queue);
    queue = NULL;
}

void queueTest() {
    Queue *queue = initQueue(5);
    printf("队列长度: %d\n", queueLength(queue));
    enQueue(queue, 'a');
    enQueue(queue, 'b');
    enQueue(queue, 'c');
    enQueue(queue, 'd');
    showQueue(queue);
    printf("出队列元素：%c\n", deQueue(queue));
    printf("出队列元素：%c\n", deQueue(queue));
    printf("出队列元素：%c\n", deQueue(queue));
    printf("队列是否为空：%s\n", isEmptyQueue(queue) == 1 ? "true" : "false");
    printf("队列长度: %d\n", queueLength(queue));
    deleteQueue(queue);
}